﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using System.Security.Cryptography;
using Microsoft.VisualBasic;

public partial class CAS : System.Web.UI.Page,IRequiresSessionState
{
    //加解密秘钥
    static string key = "LYQ57828LYQ";
    protected void Page_Load(object sender, EventArgs e)
    {
               //统一登录网址
        string ssoURL = "http://ids.nbcc.cn/sso/";
        //处理统一登录的本站地址
        string serverName=Request.ServerVariables.Get("Server_Name").ToString();
        string service = "http://" + serverName+"/cas.aspx";
        //票据
        string ticket = Request.QueryString["ticket"];
        Response.Clear();

       // getInfo("A11004");
        if (ticket== ""||ticket==null)
        {
            Response.Redirect(ssoURL+"login?service="+service);
            Response.End();
        }
        else
        {
            string validURL=ssoURL+"serviceValidate?ticket="+ticket+"&service="+service;
            string fileConent = getHtml(validURL, "utf-8");
            string pattern = @"<cas\:user>([\S]{6})</cas\:user>";

             Match match = Regex.Match(fileConent,pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
             string username="";
             if (match.Success)
             {
                 username= match.Groups[1].Value.Trim();

                string cTable2 = "select GH,XM,XZ_XB,密码 from JS_B_教师基本情况 where 是否删除=0";
                DataTable dt = getDataTable(cTable2);
                int num1 = 0;
                int num2 = checked (dt.Rows.Count - 1);
                int index = num1;
                while (index <= num2)
                {
                   //把姓名和工号解码出来
                  dt.Rows[index]["GH"] = (object) n参数(DeWithJava(key, dt.Rows[index]["GH"].ToString()), ",", 2);
                  dt.Rows[index]["XM"] = (object) n参数(DeWithJava(key,dt.Rows[index]["XM"].ToString()), ",", 2);
                  //checked检查是否溢出
                  checked { ++index; }
                }
                DataTable dataTable2 = getDataTable(dt, "GH='" +username+"'");
                if (dataTable2.Rows.Count > 0)
                {
                    this.Session["UserID"] = (object)username;
                    this.Session["UserXB"] = (object)dataTable2.Rows[0]["XZ_XB"].ToString();
                    this.Session["UserXM"] = (object)dataTable2.Rows[0]["XM"].ToString();
                    this.Session["oRsQX"] = (object)GetQX(username);
                    this.Session["WinSize"] = (object)"1400";

                //    Response.Write("用户ID：" + this.Session["UserID"] + "</br>");
                //    Response.Write("姓名：" + this.Session["UserXM"] + "</br>");
                //    Response.Write("性别：" + this.Session["UserXB"] + "</br>");
               //     Response.Write("权限：" + this.Session["oRsQX"] + "</br>");
               //     Response.Write("窗口大小：" + this.Session["WinSize"] + "</br>");

                    DataTable dataTable3 = getDataTable(saveTips( this.Session["UserXM"].ToString(),this.Session["UserID"].ToString()));
                    if (Conversion.Val(dataTable3.Rows[0]["我的工作"].ToString()) > 0.0)
                        this.Page.Response.Redirect("http://" + serverName + "/Set/MyJob.aspx", false);
                    else if (Conversion.Val(dataTable3.Rows[0]["我的审核"].ToString()) > 0.0)
                        this.Page.Response.Redirect("http://" + serverName + "/Set/DataAuditing.aspx", false);
                    else if (Conversion.Val(dataTable3.Rows[0]["我的采集"].ToString()) > 0.0)
                        this.Page.Response.Redirect("http://" + serverName + "/Set/DataMaintenance.aspx", false);
                    else
                        this.Page.Response.Redirect("http://" + serverName + "/Set/Main.aspx", false);


                  //  Response.Redirect("http://" + serverName + "/Set/Main.aspx");
                    Response.End();
                }
                
             }
             else{
                  Response.Write("获取用户名失败");
             }         
            Response.End();

        }
       
    }


    /// <summary>
    /// 从指定网址中获取网页内容。
    /// </summary>
    /// <param name="url">网址</param>
    /// <param name="charSet">指定的字符编码格式</param>
    /// <returns>网页源代码</returns>
    public static string getHtml(string url, string charSet)
    //url是要访问的地址，charSet是目标网页的编码，如果传入的是null或者""，那就自动分析网页的编码 
    {

        WebClient myWebClient = new WebClient();
        myWebClient.Credentials = CredentialCache.DefaultCredentials;
        //获得数据
        byte[] myDataBuffer = myWebClient.DownloadData(url);
        string strWebData = Encoding.Default.GetString(myDataBuffer);

        if (charSet != null && charSet != "" && Encoding.GetEncoding(charSet) != Encoding.Default)
            strWebData = Encoding.GetEncoding(charSet).GetString(myDataBuffer);
        return strWebData;
    }

    //从数据库中获取基本信息
    public static DataView getInfo(string username)
    {
         SqlDataSource ds = new SqlDataSource();

         ds.ConnectionString = ConfigurationManager.AppSettings["cConnString"];
         ds.SelectCommand = "select GH,XM,XZ_XB from JS_B_教师基本情况 where 是否删除=0 and GH='"+EncryptWithJava(key,username)+"'";
         DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
         return dv;
    }
    //读取权限部分
    public DataTable GetQX(string username )
    {
        DataTable dataTable;
        dataTable = (DataTable)null;
        try
        {   
            string str="declare @工号 nvarchar(250) set @工号='" + username + "' declare @RecCount int,@审核通过后编辑或删除记录 nvarchar(10),@编辑或删除非本人采集的记录 nvarchar(10),@导入的数据的初始状态 nvarchar(10),@重新审核 nvarchar(10) create table #t1 (ID int IDENTITY(1,1),角色 nvarchar(250),目录编号 nvarchar(250),读取 nvarchar(10),增加 nvarchar(10),删除 nvarchar(10),编辑 nvarchar(10),批量 nvarchar(10),审核 nvarchar(10),导入 nvarchar(10),管辖部门编号集 nvarchar(max)) select @RecCount=count(*) from Set_VB_QXSZ where 工号=@工号 and 操作权限='超级用户' if @RecCount>0 begin insert into #t1 (角色,目录编号,读取,增加,删除,编辑,批量,审核,导入,管辖部门编号集) select distinct '超级用户',目录编号,读取,增加,删除,编辑,批量,审核,导入,'' from Set_VB_JSSZ where 角色名称='超级用户' goto ProEnd end select @RecCount=count(*) from Set_VB_QXSZ where 工号=@工号 and 操作权限='状态数据查看' if @RecCount>0 begin insert into #t1 (角色,目录编号,读取,增加,删除,编辑,批量,审核,导入,管辖部门编号集) select distinct '查看人',目录编号,读取,增加,删除,编辑,批量,审核,导入,'' from Set_VB_JSSZ where 角色名称='查看人' end /*本人表角色*/ insert into #t1 (角色,目录编号,读取,增加,删除,编辑,批量,审核,导入,管辖部门编号集) select 角色名称,目录编号,0,0,0,0,0,0,0,管辖部门编号 from Set_VB_JSYH where 工号=@工号 update #t1 Set 读取=c.读取,增加=c.增加,编辑=c.编辑,批量=c.批量,删除=c.删除,导入=c.导入 from #t1 z,Set_VB_JSSZ c where z.目录编号=c.目录编号 and z.角色=c.角色名称 ProEnd: select @编辑或删除非本人采集的记录=设置 from Set_VB_CS where 分类='参数' and 类型='编辑或删除非本人采集的记录' select @导入的数据的初始状态=设置 from Set_VB_CS where 分类='参数' and 类型='导入的数据初始状态' select @审核通过后编辑或删除记录=设置 from Set_VB_CS where 分类='参数' and 类型='审核通过后编辑或删除记录' select @重新审核=设置 from Set_VB_CS where 分类='参数' and 类型='重新审核' select *,isnull(@审核通过后编辑或删除记录,'禁止') as 审核通过后编辑或删除记录,isnull(@编辑或删除非本人采集的记录,'禁止') as 编辑或删除非本人采集的记录,isnull(@导入的数据的初始状态,'禁止') as 导入的数据的初始状态,isnull(@重新审核,'禁止') as 重新审核 from #t1 order by 目录编号 drop table #t1";
            dataTable=getDataTable(str);
           
           }
        catch (Exception ex)
        {
        }
        return dataTable;
    }
    //重新生成提示的语句
    private string saveTips(string XM,string userID)
    {
        string str = "/*重新生成Set_B_MyTips*/ declare @卡号 nvarchar(max),@姓名 nvarchar(max) set @卡号='" + userID + "' set @姓名='" + XM + "' declare @cSql nvarchar(max),@目录 nvarchar(max) set @目录='1.1,1.2,1.3,1.4,1.5,1.6,2.1,2.2,3.1,3.2,3.3,3.4.1,3.4.2,3.4.3,3.5,4.1,4.2,4.3,5.1.1,5.1.2,5.1.3,5.1.4,5.1.5,5.2.1,5.2.2,5.2.3,6.1,6.2,6.3.A,6.3.B,6.3.C,6.3.D,6.3.E,6.3.F,6.3.G,7.1.1,7.1.2,7.1.3,7.2,7.3.1,7.3.2,7.4,7.5.1,7.5.2,7.6.1,7.6.3,8.1,8.2,8.3,8.4,8.5,8.6,8.7,8.8,8.9,9.3,9.4,9.5,9.6.1,9.6.2,9.6.3,10.1.1,10.1.2,10.2.1,10.3,10.4,10.5,11.1,11.2,11.3,11.5,11.6,12.1' create table #目录 (ID int identity(1,1),A nvarchar(max),B nvarchar(max),C nvarchar(max),D nvarchar(max)) create table #采集 (数量 int,表名 nvarchar(max),目录编号 nvarchar(max),卡号 nvarchar(max)) create table #审核 (数量 int,表名 nvarchar(max),目录编号 nvarchar(max),卡号 nvarchar(max),部门编号 nvarchar(max)) create table #任务 (目录编号 nvarchar(max),卡号 nvarchar(max),姓名 nvarchar(max),类型 nvarchar(max),JobsID nvarchar(max)) create table #删除 (ID nvarchar(max)) insert into #目录 (C) select value as 目录编号 from dbo.Split_Text(@目录,',') update #目录 set A=c.表名 from #目录 z,Set_VB_BM c where z.C=c.目录编号 /*任务*/ insert into #任务 (目录编号,卡号,姓名,类型)\tselect 目录编号,工号,姓名,left(角色名称,2) as 类型 from Set_VB_JSYH where 工号=@卡号 and 角色名称 in ('采集人','审核人') /*采集*/ update #目录 set D='采集',B='select '+''''+C+''''+','+'count(ID),'+''''+A+''''+',建立卡号 from '+A+' where 是否删除=0 and 审核状态='+''''+'不通过'+''''+' group by 建立卡号' select @cSql='insert into #采集 (目录编号,数量,表名,卡号) '+stuff((select ' union all '+convert(nvarchar(max),B) from #目录 for xml path('')),1,11,'') exec (@cSql) /*审核*/ update #目录 set D='审核',B='select '+''''+C+''''+','+'count(ID) as 数量,BMBH as 部门编号,'+''''+replace(A,'_B_','_VB_')+''''+' from '+replace(A,'_B_','_VB_')+' where 是否删除=0 and 审核状态='+''''+'待审核'+''''+' group by BMBH' where C in ('6.1','6.2','6.3.A','6.3.B','6.3.C','6.3.D','6.3.E','6.3.F','6.3.G','7.1.1','7.1.2','7.1.3','7.2','7.4','7.5.1','7.5.2','7.6.1','7.6.3','10.1.1','11.5','11.6') update #目录 set D='审核',B='select '+''''+C+''''+','+'count(ID) as 数量,'+''''+''+''''+' as 部门编号,'+''''+A+''''+' from '+A+' where 是否删除=0 and 审核状态='+''''+'待审核'+'''' where C not in ('6.1','6.2','6.3.A','6.3.B','6.3.C','6.3.D','6.3.E','6.3.F','6.3.G','7.1.1','7.1.2','7.1.3','7.2','7.4','7.5.1','7.5.2','7.6.1','7.6.3','10.1.1','10.1.2','10.2.1','11.5','11.6') delete from #目录 where isnull(C,'') in ('10.1.2','10.2.1') select ID,XSXH,SPACE(80) as ZYDM,SPACE(80) as ZYFXDM,SPACE(80) as BMBH into #辍学 from PG_B_CXXS where 审核状态='待审核' and 是否删除=0 select ID,XSXH,SPACE(80) as ZYDM,SPACE(80) as ZYFXDM,SPACE(80) as BMBH into #就业 from PG_B_XSJYXX where 审核状态='待审核' and 是否删除=0 update #辍学 set BMBH=c.BMBH,ZYDM=c.ZYDM,ZYFXDM=c.ZYFXDM from #辍学 z,JS_VB_在校生信息 c where z.XSXH=c.XSXH update #就业 set BMBH=c.BMBH,ZYDM=c.ZYDM,ZYFXDM=c.ZYFXDM from #就业 z,JS_VB_在校生信息 c where z.XSXH=c.XSXH insert into #目录 (B) select 'select '+''''+'10.1.2'+''''+','+'count(ID) as 数量,BMBH as 部门编号,'+''''+'#就业'+''''+' from #就业 group by BMBH' insert into #目录 (B) select 'select '+''''+'10.2.1'+''''+','+'count(ID) as 数量,BMBH as 部门编号,'+''''+'#辍学'+''''+' from #辍学 group by BMBH' select @cSql='insert into #审核 (目录编号,数量,部门编号,表名) '+stuff((select ' union all '+convert(nvarchar(max),B) from #目录 for xml path('')),1,11,'') exec (@cSql) select 工号,目录编号,value as 部门编号 into #权限1 from (select 工号,目录编号,管辖部门编号 from Set_VB_JSYH where 角色名称='审核人') a cross apply Split_Text(管辖部门编号,',') select 目录编号,工号集 into #权限2 from (select 目录编号,stuff((select ','+工号 from #权限1 t where 目录编号=#权限1.目录编号 for xml path('')),1,1,'') as 工号集 from #权限1 where isnull(部门编号,'')='' group by 目录编号) t select 目录编号,工号集 into #权限3 from (select 目录编号,部门编号,stuff((select ','+工号 from #权限1 t where 目录编号=#权限1.目录编号 and 部门编号=#权限1.部门编号 for xml path('')),1,1,'') as 工号集 from #权限1 where isnull(部门编号,'')<>'' and isnull(部门编号,'')='所有部门' group by 目录编号,部门编号) t select 目录编号,工号集,部门编号 into #权限4 from (select 目录编号,部门编号,stuff((select ','+工号 from #权限1 t where 目录编号=#权限1.目录编号 and 部门编号=#权限1.部门编号 for xml path('')),1,1,'') as 工号集 from #权限1 where isnull(部门编号,'')<>'' and isnull(部门编号,'')<>'所有部门' group by 目录编号,部门编号) t update #审核 set 卡号=c.工号集 from #审核 z,#权限2 c where z.目录编号=c.目录编号 update #审核 set 卡号=c.工号集 from #审核 z,#权限3 c where z.目录编号=c.目录编号 update #审核 set 卡号=case when isnull(卡号,'')='' then '' else 卡号+','end +c.工号集 from #审核 z,#权限4 c where z.目录编号=c.目录编号 and z.部门编号=c.部门编号 truncate table Set_B_MyTips insert into Set_B_MyTips (类型,编号,数量,卡号) select '我的审核',目录编号,数量,卡号 from #审核 where 数量>0 insert into Set_B_MyTips (类型,编号,数量,卡号) select '我的采集',目录编号,数量,卡号 from #采集 where 数量>0 /*我的工作*/ insert into Set_B_MyJob (JobsID,责任人卡号,责任人姓名,任务状态) select ID,@卡号,@姓名,'未接受' from Set_B_Jobs where 任务类型 like '%个人%' and ID not in (select JobsID from Set_B_MyJob where 责任人卡号=@卡号) insert into Set_B_MyJob (JobsID,责任人卡号,责任人姓名,任务状态) select B.ID,A.卡号,A.姓名,'未接受' from #任务 A,Set_B_Jobs B where A.目录编号=B.目录编号 and left(A.类型,2)=right(B.任务类型,2) and convert(varchar(50),B.ID)+A.卡号 not in (select convert(varchar(50),JobsID)+责任人卡号 from Set_B_MYJob where 责任人卡号=@卡号) insert into #删除 (ID) select ID from Set_VB_MyJob where 责任人卡号=@卡号 and right(任务类型,2) in ('采集','审核') and 目录编号+责任人卡号+right(任务类型,2) not in (select 目录编号+责任人卡号+类型 from #任务 where 类型 in ('采集','审核')) delete from Set_B_MyJob where JobsID not in (select ID from Set_B_Jobs) or isnull(责任人卡号,'')='' or ID in (select ID from #删除) /*输出*/ declare @我的工作 int,@我的采集 int,@我的审核 int,@超级用户 int select @超级用户=isnull(count(*),0) from Set_VB_QXSZ where 工号=@卡号 and 操作权限='超级用户' if @超级用户>0 begin select @我的采集=sum(数量) from Set_B_MyTips where 类型='我的采集' select @我的审核=sum(数量) from Set_B_MyTips where 类型='我的审核' end else begin select @我的采集=sum(数量) from Set_B_MyTips where 类型='我的采集' and 卡号+',' like '%'+@卡号+',%' select @我的审核=sum(数量) from Set_B_MyTips where 类型='我的审核' and 卡号+',' like '%'+@卡号+',%' end select @我的工作=count(*) from Set_VB_MyJob where 责任人卡号=@卡号 and 任务状态 in ('未接受','进行中') select isnull(@我的工作,0) as 我的工作,isnull(@我的采集,0) as 我的采集,isnull(@我的审核,0) as 我的审核,@超级用户 as 超级用户 drop table #删除 drop table #任务 drop table #权限1 drop table #权限2 drop table #权限3 drop table #权限4 drop table #辍学 drop table #就业 drop table #审核 drop table #目录 drop table #采集";
        return str;    
    }

    /// <summary>
    /// 读取数据到dataTable
    /// </summary>
    /// <param name="sqlStr">查询字符串</param>
    /// <returns></returns>
    public DataTable getDataTable(string sqlStr)
    {
        DataTable dataTable = new DataTable();
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = ConfigurationManager.AppSettings["cConnString"];
        SqlCommand selectCommand = new SqlCommand(sqlStr, connection);
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectCommand);
        DataSet dataSet = new DataSet();
        try
        {
            connection.Open();
            sqlDataAdapter.Fill(dataSet);
            dataTable = dataSet.Tables[0];
        }
        catch (Exception ex)
        {
           
        }
        finally
        {
            connection.Close();
            selectCommand.Dispose();
        }
        return dataTable;
    }

    public DataTable getDataTable(DataTable dt, string condition)
    {
      DataTable dataTable1;
      try
      {
        DataTable dataTable2 = new DataTable();
        DataTable dataTable3 = dt.Clone();
        DataRow[] dataRowArray = dt.Select(condition);
        int num1 = 0;
        int num2 = checked (dataRowArray.Length - 1);
        int index = num1;
        while (index <= num2)
        {
          dataTable3.ImportRow(dataRowArray[index]);
          checked { ++index; }
        }
        dataTable1 = dataTable3;
      }
      catch (Exception ex)
      {
          dataTable1=null;
      }
      return dataTable1;
    }
    //加密方法
    private static string EncryptWithJava(string key, string str)
    {
        if (key.Length < 8 || string.IsNullOrEmpty(str))
            throw new Exception("加密key小于8或者加密字符串为空！");
        byte[] bytes1 = Encoding.UTF8.GetBytes(key.Substring(0, 8));
        byte[] bytes2 = Encoding.UTF8.GetBytes(key.Substring(0, 8));
        byte[] bytes3 = Encoding.UTF8.GetBytes(str);
        string empty;
        try
        {
            DESCryptoServiceProvider cryptoServiceProvider = new DESCryptoServiceProvider();
            cryptoServiceProvider.Padding = PaddingMode.PKCS7;
            cryptoServiceProvider.Mode = CipherMode.ECB;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, cryptoServiceProvider.CreateEncryptor(bytes1, bytes2), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(bytes3, 0, bytes3.Length);
                    cryptoStream.FlushFinalBlock();
                    StringBuilder stringBuilder = new StringBuilder();
                    byte[] array = memoryStream.ToArray();
                    int index = 0;
                    while (index < array.Length)
                    {
                        byte num = array[index];
                        stringBuilder.AppendFormat("{0:x2}", (object)num);
                        checked { ++index; }
                    }
                    empty = stringBuilder.ToString();
                }
            }
        }
        catch (Exception ex)
        {
            empty = string.Empty;
        }
        return empty;
    }
    //转换
    private static byte[] strToToHexByte(string hexString)
    {
        hexString = hexString.Replace(" ", "");
        if (hexString.Length % 2 != 0)
            hexString += " ";
        byte[] numArray = new byte[checked(unchecked(hexString.Length / 2) - 1 + 1)];
        int num1 = 0;
        int num2 = checked(numArray.Length - 1);
        int index = num1;
        while (index <= num2)
        {
            numArray[index] = Convert.ToByte(hexString.Substring(checked(index * 2), 2), 16);
            checked { ++index; }
        }
        return numArray;
    }
    //解密
    private static string DeWithJava(string key, string str)
    {
        if (key.Length < 8 || string.IsNullOrEmpty(str))
            throw new Exception("加密key小于8或者加密字符串为空！");
        byte[] toHexByte = strToToHexByte(str);
        byte[] bytes1 = Encoding.UTF8.GetBytes(key.Substring(0, 8));
        byte[] bytes2 = Encoding.UTF8.GetBytes(key.Substring(0, 8));
        Encoding.UTF8.GetBytes(str);
        string empty;
        try
        {
            DESCryptoServiceProvider cryptoServiceProvider = new DESCryptoServiceProvider();
            cryptoServiceProvider.Padding = PaddingMode.PKCS7;
            cryptoServiceProvider.Mode = CipherMode.ECB;
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, cryptoServiceProvider.CreateDecryptor(bytes1, bytes2), CryptoStreamMode.Write);
            cryptoStream.Write(toHexByte, 0, toHexByte.Length);
            cryptoStream.FlushFinalBlock();
            empty = Encoding.UTF8.GetString(memoryStream.ToArray());
        }
        catch (Exception ex)
        {
            empty = string.Empty;
        }
        return empty;
    }

    //参数
    public string n参数(string n字符, string n分隔, int n位置)
    {
      int num1;
      string str1;
      try
      {
        string str2 = n分隔;
        int num2 = Strings.Len(n分隔);
        int num3 = checked ((int) Math.Round(unchecked ((double) checked (Strings.Len(n字符) - Strings.Len(Strings.Replace(n字符, n分隔, "", 1, -1, CompareMethod.Binary))) / (double) num2 + 1.0)));
        string str3;
        if (n位置 > num3)
        {
          str3 = "";
        }
        else
        {
          string str4 = n字符;
          int num4 = 1;
          int num5 = checked (n位置 - 1);
          int num6 = num4;
          while (num6 <= num5)
          {
            string Expression = Strings.Mid(str4, 1, str4.IndexOf(str2));
            str4 = Strings.Right(str4, checked (Strings.Len(str4) - Strings.Len(Expression) - num2));
            checked { ++num6; }
          }
          switch (str4.IndexOf(str2))
          {
            case -1:
              str3 = str4;
              break;
            case 0:
              str3 = "";
              break;
            default:
              str3 = Strings.Mid(str4, 1, str4.IndexOf(str2));
              break;
          }
        }
        num1 = 100;
        str1 = str3;
      }
      catch (Exception ex)
      {
       
        str1="";
       
      }
      return str1;
    }
}